package com.yu8home.mq.rabbit;

import cn.hutool.core.util.IdUtil;
import com.yu8home.mq.rabbit.ttl.QueueEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rabbit")
@Slf4j
public class RabbitController {
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/a")
    public void a() throws InterruptedException {
        String msg = "yu8home.aaaa";
        log.info("发送：{}", msg);
        for (int i = 0; i < 10; i++) {
            amqpTemplate.convertAndSend("yu8home.aaaa", msg + "==" + i);
        }
    }


    @GetMapping("/b")
    public void b() {
        String msg = "bbbb";
        log.info("发送：{}", msg);
        for (int i = 0; i < 10; i++) {
            amqpTemplate.convertAndSend("yu8home.topic", "yu8home.topic.bbbb", msg);
        }
    }


    @GetMapping("/c")
    public void c() {
        String msg = "cccc";
        log.info("发送：{}", msg);
        amqpTemplate.convertAndSend("yu8home.topic", "yu8home.topic.cccc", msg);
    }


    @GetMapping("/xy")
    public void xy() {
        String msg = "xy";
        log.info("发送：{}", msg);
        amqpTemplate.convertAndSend("yu8home.fanout", "", msg);
    }


    @GetMapping("/ttl")
    public void ttl() {
        String msg = "ttl";
        log.info("发送：{}", msg);
        rabbitTemplate.convertAndSend(QueueEnum.ORDER_TTL.getExchange(), QueueEnum.ORDER_TTL.getRouteKey(), msg, t -> {
            t.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
            t.getMessageProperties().setExpiration("5000");// 同时配置了 队列的TTL 和 消息的TTL，则较小的那个值会被使用
            log.info("ttl延迟队列");
            return t;
        }, new CorrelationData(IdUtil.fastSimpleUUID()));
    }


    @GetMapping("/delayed")
    public void delayed() {
        String msg = "delayed";
        log.info("发送：{}", msg);
        rabbitTemplate.convertAndSend(QueueEnum.ORDER_DELAYED.getExchange(), QueueEnum.ORDER_DELAYED.getRouteKey(), msg, t -> {
            t.getMessageProperties().setHeader("x-delay", 10 * 1000);
            log.info("delayed插件延迟队列");
            return t;
        }, new CorrelationData(IdUtil.fastSimpleUUID()));
    }

}
